package com.weishuang.monitor.leader.config.security;

import com.weishuang.monitor.leader.config.dto.CustomUserDetails;
import com.weishuang.monitor.leader.entity.SysUser;
import com.weishuang.monitor.leader.service.SysCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * 获取用户信息进行登录验证服务类
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private SysCacheService sysCacheService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser one = sysCacheService.getUser(s);
        if (one == null) {
            return null;
        }else{
            //默认给一个LEADER角色，todo 如果所有接口都给与了权限校验，这个地方就不用给了。
            Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_LEADER"));
            return new CustomUserDetails(one.getId(),one.getUsername(), one.getPassword(), one.getRealName(),one.getIsDefault(),grantedAuthorities);
        }
    }
}
